<template>
    <div class="substitute" v-loading="loading">
        <div class="height">发布代取</div>
        <div class="addressBox" @click="addressListLink" v-if="hasAddress">
            <div class="nameAndPhone">
                <span>收件人:{{addressList.name}}</span>
                <span>{{addressList.phone}}</span>
            </div>
            <div class="addressText">
                <i class="el-icon-location-outline"></i>
                <span>收件人地址:{{addressList.address}}</span>
                <i class="el-icon-arrow-right"></i>
            </div>
        </div>
        <div class="addressBox" @click="addressListLink" v-if="!hasAddress">
            <div class="pladd">
                <i class="el-icon-circle-plus"></i>
                <span>请添加收件人地址</span>
                <i class="el-icon-arrow-right"></i>
            </div>
        </div>
        <div class="formBox" id="formBox">
            <el-form ref="form" :model="formInline" label-width="100px">
                <el-form-item label="取件地点：">
                    <el-select v-model="formInline.mailCompany" placeholder="取件地点">
                        <el-option v-for="(item,index) in mailCompany" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="收货时间：">
                    <el-select v-model="receiveId" @change="receiveTime()" placeholder="收货时间">
                        <el-option v-for="(item,index) in receiveDate" :key="index" :label="item.dicCode" :value="index">
                            <span style="float: left">{{ item.dicCode }}</span>
                            <span style="float: right; color: #F56C6C; font-size: 13px">{{ item.value }}元</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="货物大小：">
                    <el-select v-model="goodsSize" @change="receiveTime()" placeholder="货物大小">
                        <el-option v-for="(item,index) in goodsSizes" :key="index" :label="item.label" :value="item.price">
                            <span style="float: left">{{ item.label }}</span>
                            <span style="float: right; color: #F56C6C; font-size: 13px">+{{ item.price }}</span>
                        </el-option>
                    </el-select>
                    <i class="el-icon-question colorY" @click="dialogVisible = true"></i>
                </el-form-item>
                <el-form-item label="代取费用：">
                    <el-input :disabled="true" v-model="amount" placeholder="代取费用"></el-input>
                    <!-- <el-select  v-model="formInline.amount" placeholder="代取费用">
                        <el-option v-for="(item,index) in amount" :key="index" :label="item+'元'" :value="item"></el-option>
                    </el-select> -->
                </el-form-item>
                <el-form-item label="取货码：">
                    <el-input v-model="formInline.mailCode" placeholder="取货码"></el-input>
                </el-form-item>
            </el-form>
            
        </div>
        <div class="btn" align="center">
            <button id="send" @click="sendOpen">确认发布</button>
        </div>
        <div class="footerFix">
            <div class="taBox">
                <div class="taBoxItem active" @click="tab(0)">
                    <i class="iconfont icon-7"></i>
                    <span>代取</span>
                </div>
                <!--<div class="taBoxItem" @click="tab(1)">
                    <i class="iconfont icon-youjian"></i>
                    <span>邮寄</span>
                    
                </div>-->
                <div class="taBoxItem" @click="tab(2)">
                    <i class="iconfont icon-icon-test"></i>
                    <span>我的</span>
                    
                </div>
            </div>
        </div>

        <el-dialog title="提示" :visible.sync="dialogVisible" width="90%">
          <div style="text-align: left;">
            <p>小件：体积不超过普通单件鞋盒；</p>
            <p>中件：体积不超过普通拉杆箱1/2；</p>
            <p>大件：体积不超过普通拉杆箱；</p>
            <p>特件：体积不超过普通拉杆箱*2；</p>
          </div>
            
        </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'substitute',
  data () {
    return {
        dialogVisible: false,
        successBox: '',
        inputNums: '',
        orderId: '',
        appid: 'wx7bcf48887c6bacf2',
        appsecret: '646d609205fd26f406aa3623d1559539',
        addressList: {},
        hasAddress: false,
        formInline: {
            mailCompany: '【菜鸟驿站】南苑商务中心二楼',
            amount: '',
            receiveDate: '',
            mailCode: '',
        },
        goodsSizes: [{label:'小件',price:0},{label:'中件',price:3},{label:'大件',price:5},{label:'特件',price:8}],
        goodsSize: 0,
        receiveId: 0, 
        mailCompany: ['【菜鸟驿站】南苑商务中心二楼','【中国邮政】南苑商务中心一楼','【申通快递】中工北门鲜果驿站','【京东快递】北苑国教楼一楼','【百世邻里】升达大门向南30米','【其他快递】中工北门对面'],
        amount: '',
        receiveDate: [],
        package: '',
        getBrandWCPayRequest: {},
        loading: false,
    }
  },
  computed:{
    openId() {
      return this.$store.state.app.openId
    },
    token() {
      return this.$store.state.app.token
    },
    userId() {
      return this.$store.state.app.userId
    },
  },
  mounted(){
    this.init();
  },
  methods:{
    init(){
      let search = window.location.search;
        this.loading = true;
        // console.log('openId:'+this.openId,'token:'+this.token,'userId:'+this.userId)
        if(!this.openId){
            search = search.split("?")[1];
            let searchArr = search.split("&");
            
            // let serchObj = {};
            // serchObj[searchArr[0].split("=")[0]] = searchArr[0].split("=")[1];
            // serchObj[searchArr[1].split("=")[0]] = searchArr[1].split("=")[1];
            if(searchArr[0].split("=")[1]){
                this.accessToken(searchArr[0].split("=")[1])
            }
        }else{
          
          if(this.userId&&this.token){
              this.getDefaultMailAddress(this.userId,this.token);
          }else{
              this.hasAddress = false;
          }
        }
        
             
        
        

    },
    querySubPrice(){
      this.axios({
            method: 'post',
            url: '/app/app/common/querySubPrice',
            headers: {'userId': this.userId,'token': this.token},
            data: {
                
            }
        }).then(res =>{
            // console.log(res.data.data.prices);
            this.receiveDate = res.data.data.prices;
                this.receiveId = 0;
                this.receiveTime();
            

        }) 
    },
      sendOpen() {
        let sendData = {}
                    sendData.name = this.addressList.name,//姓名
                    sendData.phone = this.addressList.phone,//电话
                    sendData.address = this.addressList.address,
                    sendData.amount = this.formInline.amount,
                    sendData.mailCode = this.formInline.mailCode,
                    sendData.mailCompany = this.formInline.mailCompany,//快递公司
                    sendData.receiveDate = this.formInline.receiveDate
				this.axios({
				    method: 'post',
				    url: '/app/wx/gzh/pushMailDemand',
				    headers: {'userId': this.userId,'token': this.token},
				    data: sendData
				}).then(res =>{
				    console.log(res.data);
					if(res.data.message.code == 200){
						this.prepayment(res.data.data)
					}else{
						this.$message({message: '发布失败！',type: 'warning'});
					}
				    
				})
        
    },
	// 公众号预支付接口
	prepayment(data){
		this.orderId = data.MailDemand.id
		this.axios({
		    method: 'post',
		    url: '/app/app/weixin/weixinApiPay',
		    headers: {'userId': this.userId,'token': this.token},
		    data: {
				'orderId': data.MailDemand.id
			}
		}).then(res =>{
		    // console.log(res.data);
			this.getBrandWCPayRequest = res.data.data;
		    this.pay();
		})
	},
	pay(){
		if (typeof WeixinJSBridge == "undefined"){
		   if( document.addEventListener ){
			   document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
		   }else if (document.attachEvent){
			   document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady); 
			   document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
		   }
		}else{
		   this.onBridgeReady();
		}
	},
	onBridgeReady(){
    	let that = this;
		let data = this.getBrandWCPayRequest;
		WeixinJSBridge.invoke(
		  'getBrandWCPayRequest', {
			 "appId": data.appId,     //公众号名称，由商户传入     
			 "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数     
			 "nonceStr": data.nonceStr, //随机串     
			 "package": data.package,     
			 "signType":"MD5",         //微信签名方式：     
			 "paySign": data.paySign //微信签名 
		  },
		  function(res){
//		  	that.$message(res.err_msg);
		  if(res.err_msg == "get_brand_wcpay_request:ok" ){
		  // 使用以上方式判断前端返回,微信团队郑重提示：
				//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
				that.weixinCallBack()
		  } 
	   }); 
	},
	weixinCallBack(){
		this.axios({
		    method: 'post',
		    url: '/app/app/weixin/callBack',
		    headers: {'userId': this.userId,'token': this.token},
		    data: {
				'orderId': this.orderId
			}
		}).then(res =>{
		    // console.log(111,res);
        // this.$message("OK!!!")
        this.$router.push('/order');
			
		})
	},
    accessToken(code){
        this.axios.get('/api/sns/oauth2/access_token',{
            params:{
                appid:this.appid,
                secret:this.appsecret,
                code: code,
                grant_type: 'authorization_code'
            }
        })
        .then(res =>{
            // console.log(res);
            if(res.data){
              localStorage.setItem('openId', res.data.openid);
              this.$store.commit('inopenId',res.data.openid);
              // console.log(this.openId)
              this.userinfo(res.data);
            }
        })
    },
    userinfo(data){
        this.axios.get('/api/sns/userinfo',{
            params:{
                access_token: data.access_token,
                openid: data.openid,
                lang: 'zh_CN',
            }
        })
        .then(res =>{
            // console.log(res.data);
            if(res.data){
              localStorage.setItem('nickname', res.data.nickname);
              localStorage.setItem('headimgurl', res.data.headimgurl);
              this.getUserByOpenid();
            }
        })
    },
    getUserByOpenid(){
        this.axios.post('/app/app/user/getUserByOpenid',{
                openId: this.openId,
        })
        .then(res =>{
          let userData = res.data;
            // console.log(userData);
            if(userData.data){
              this.$store.commit('inuserId',userData.data.userId);
              this.$store.commit('intoken',userData.data.token);
                localStorage.setItem('userId', userData.data.userId);
                localStorage.setItem('token', userData.data.token);
                // console.log(this.userId,this.token);
                this.getDefaultMailAddress(userData.data.userId,userData.data.token)
            }else{
                this.loading = false;
                this.$router.push('/bindPhone');
            }
        })
    },

    addressListLink(){
        this.$router.push('/addressList')
    },
    tab(index){
          if(index == 0){
              this.$router.push("/")
          }else if(index == 1){
			window.location.href = 'https://m.kuaidi100.com/order/market/eb.jsp?sign=TRz9921Market'	
          }else{
             this.$router.push("/personal")  
          }
    },
    getDefaultMailAddress(userId,token){
        this.querySubPrice()
        this.axios({
            method: 'post',
            url: '/app/campus/mailAddress/getDefaultMailAddress',
            headers: {'userId': userId,'token': token},
            data: {
              'openId': this.openId
            }
        }).then(res =>{
            // console.log(res.data);
            this.loading = false;
            if(res.data.data){
                this.addressList = res.data.data;
                this.hasAddress = true;
            }else if(res.data.message.code == 401){
                this.getUserByOpenid();
            }else{
                this.$router.push('/addressList')
            }
			
        })
    },
    receiveTime(){
                for(let i = 0;i < this.receiveDate.length;i++){
                    if(i == this.receiveId){
                        this.goodsSize = this.goodsSize - 0;
                        this.receiveDate[i].value = this.receiveDate[i].value -0;
                        let price = this.receiveDate[i].value + this.goodsSize;
                        this.formInline.amount = price;
                        this.amount = price + '元'
                        this.formInline.receiveDate = this.receiveDate[i].dicCode;
                    }
                }
    },


  },
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.substitute{padding-bottom: 60px;}
.height{
  background: #fcd927;height: 42px;font-size: 16px;line-height: 42px;text-align: center;color: #fff;padding: 0 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);margin-bottom: 3px;
}
.addressBox{box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);background: #fff;margin-bottom: 3px;}
.nameAndPhone{display: flex;justify-content: space-between;padding: 15px 40px 5px;font-size: 15px;font-weight: bold;}
.addressText{text-align: left;padding: 5px 0px 15px;font-size: 14px;display: flex;align-items: center;}
.addressText i{width: 40px;text-align: center;font-size: 18px;}
.addressText span{flex-grow: 1;}
.pladd{text-align: left;padding: 10px 0px;font-size: 14px;display: flex;align-items: center;}
.pladd i{width: 40px;text-align: center;font-size: 18px;}
.pladd i.el-icon-circle-plus{color: crimson;}
.pladd span{flex-grow: 1;}
.formBox{padding: 30px 30px 20px 0;}
.btn{padding-top: 20px;}
#send{width: 280px;height: 42px;background: crimson;border-radius: 4px;text-align: center;line-height: 42px;box-shadow: 0 2px 12px 0 rgba(0,0,0,.2);font-size: 16px;color: #fff;}
.message{position: fixed;top: 80px;left: 50%;margin-left: -130px;width: 260px;height: 40px;z-index: 999;text-align: left;line-height: 40px;display: none;border-radius: 4px;font-size: 12px;box-shadow: 0 2px 12px 0 rgba(0,0,0,.2);}
.passWord{text-align: center;}
.passWord input{background-color: #fff;border-radius: 4px;border: 1px solid #dcdfe6;box-sizing: border-box;color: #606266;display: inline-block;height: 40px;line-height: 40px;padding: 0 15px;width: 225px;letter-spacing: 28px;}
.footerFix{height: 50px;position: fixed;bottom: 0px;background: #fff;z-index: 99;width: 100%;box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);}
.taBox{display: flex;height: 100%;border-top: 1px solid #ddd;}
.taBoxItem{flex-grow: 1;text-align: center;font-size: 12px;border-right: 1px solid #ddd;display: flex;flex-direction: column;justify-content: center;}
.taBoxItem.active{color: #fcd927;}
.taBoxItem i{font-size: 24px;}
.taBoxItem:focus{background: #ddd;}
.taBoxItem:last-child{border-right:none;}
.colorY{color: #fcd927;margin-left: 10px;}
.el-select{width: 100%;}
</style>
<style>
  #formBox .el-form .el-form-item .el-form-item__content{display: flex; align-items: center;}
</style>
